/**
 * Get favorites
 */

var getFavs = function(id, options){
	this.id = id;
	this.success = options.success;
	this.error = options.error;
	this.getFavorites();
};

getFavs.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

getFavs.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

getFavs.prototype.check = function(nextStatement){
	var self = this;
	Mysql.query("SELECT COUNT(*) as c1 FROM Account WHERE id="+Mysql.escape(self.id)+" LIMIT 1")
	.on('error', function(error){
		console.log('Mysql error: '+error);
		self._error(9999, 'Mysql error');
	})
	.on('result', function(result){
		if(result['c1'] == 0) {
			self._error(9999, 'Account not found');
			return;
		}
		nextStatement();
	});
};

getFavs.prototype.getFavorites = function(){
	var self = this;
	self.check(function(){
		Mysql.query("SELECT COUNT(*) as c1 FROM Favorite WHERE Favorite.accountId="+Mysql.escape(self.id))
		.on('error', function(error){
			console.log('Mysql error: '+error);
			self._error(9999, 'Mysql error');
		})
		.on('result', function(result){
			if(result['c1'] == 0) {
				self._error(9999, 'Not found favorites');
				return;
			}
			var length = result['c1'];
			Mysql.query("SELECT Favorite.id, Place.id, Place.name FROM Favorite JOIN Place ON Place.id=Favorite.placeId WHERE Favorite.accountId="+Mysql.escape(self.id))
			.on('error', function(error){
				console.log('Mysql error: '+error);
				self._error(9999, 'Mysql error');
			})
			.on('result', function(result){
				self._success({ data: result, length: length });
			});
		});
	});
};

module.exports = getFavs;